// pages/refunds/refunds.ts
import { MerchantAPI } from '../../utils/api'

interface RefundApplication {
  refundId: string;
  orderId: string;
  orderTime: string;
  refundType: number;
  refundTypeText: string;
  refundReason: string;
  refundDescription?: string;
  refundAmount: number;
  status: number;
  statusText: string;
  applyTime: string;
  customerInfo: {
    name: string;
    phone: string;
  };
  orderInfo?: {
    orderTime: string;
    paymentMethod: string;
    items: Array<{
      productName: string;
      quantity: number;
      price: number;
    }>;
    totalAmount: number;
  };
  refundEvidence?: Array<{
    type: string;
    url: string;
  }>;
}

interface RefundsPageData {
  hasLogin: boolean;
  loading: boolean;
  refreshing: boolean;
  
  // 统计数据
  stats: {
    totalApplications: number;
    pendingCount: number;
    processedCount: number;
    refundedCount: number;
  };
  
  // 退款申请列表
  refunds: RefundApplication[];
  filteredRefunds: RefundApplication[];
  
  // 筛选
  activeStatus: string;
  
  // 分页
  page: number;
  limit: number;
  hasMore: boolean;
  
  // 弹窗状态
  showDetailModal: boolean;
  showReasonModal: boolean;
  refundDetail: RefundApplication | null;
  processingRefund: RefundApplication | null;
  currentAction: string;
  processReason: string;
}

Page({
  data: {
    hasLogin: false,
    loading: false,
    refreshing: false,
    
    // 统计数据
    stats: {
      totalApplications: 0,
      pendingCount: 0,
      processedCount: 0,
      refundedCount: 0
    },
    
    // 退款申请列表
    refunds: [],
    filteredRefunds: [],
    
    // 筛选
    activeStatus: '',
    
    // 分页
    page: 1,
    limit: 10,
    hasMore: true,
    
    // 弹窗状态
    showDetailModal: false,
    showReasonModal: false,
    refundDetail: null,
    processingRefund: null,
    currentAction: '',
    processReason: ''
  } as RefundsPageData,

  onLoad() {
    this.checkLoginStatus();
    if (this.data.hasLogin) {
      this.loadRefunds();
    }
  },

  onShow() {
    this.checkLoginStatus();
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('merchantToken');
    const userInfo = wx.getStorageSync('merchantUserInfo');
    
    if (token && userInfo) {
      this.setData({
        hasLogin: true
      });
    } else {
      this.setData({
        hasLogin: false
      });
    }
  },

  // 去登录页
  goToLogin() {
    wx.navigateTo({
      url: '/pages/auth/auth'
    });
  },

  /**
   * 加载退款申请列表
   */
  async loadRefunds(isRefresh = false) {
    if (isRefresh) {
      this.setData({
        page: 1,
        refunds: [],
        hasMore: true
      });
    }

    this.setData({ 
      loading: true,
      refreshing: isRefresh 
    });

    try {
      // 调用后端API：/merchant/refund/applications
      // const response = await MerchantAPI.getRefundApplications({
      //   status: this.data.activeStatus,
      //   page: this.data.page,
      //   limit: this.data.limit
      // });

      // 模拟退款申请数据
      const mockRefunds: RefundApplication[] = [
        {
          refundId: "REF1001",
          orderId: "123456789",
          orderTime: "2023-11-10 09:45:12",
          refundType: 1,
          refundTypeText: "仅退款",
          refundReason: "餐品错送/漏送",
          refundDescription: "收到的套餐缺少薯条，联系骑手未解决，希望能够退款处理。",
          refundAmount: 44.90,
          status: 0,
          statusText: "退款处理中",
          applyTime: "2023-11-15 14:30:22",
          customerInfo: {
            name: "张先生",
            phone: "138****6789"
          },
          orderInfo: {
            orderTime: "2023-11-10 09:45:12",
            paymentMethod: "微信支付",
            items: [
              {
                productName: "香辣鸡腿堡套餐",
                quantity: 1,
                price: 39.90
              },
              {
                productName: "中杯可乐",
                quantity: 1,
                price: 5.00
              }
            ],
            totalAmount: 44.90
          },
          refundEvidence: [
            {
              type: "image",
              url: "https://example.com/evidence1.jpg"
            }
          ]
        },
        {
          refundId: "REF1002",
          orderId: "123456788",
          orderTime: "2023-11-12 12:20:00",
          refundType: 1,
          refundTypeText: "仅退款",
          refundReason: "商品质量问题",
          refundAmount: 25.80,
          status: 2,
          statusText: "已退款",
          applyTime: "2023-11-12 13:30:00",
          customerInfo: {
            name: "李女士",
            phone: "139****5678"
          }
        }
      ];

      const mockStats = {
        totalApplications: 25,
        pendingCount: 8,
        processedCount: 12,
        refundedCount: 15
      };

      const newRefunds = isRefresh ? mockRefunds : [...this.data.refunds, ...mockRefunds];
      
      this.setData({
        refunds: newRefunds,
        stats: mockStats,
        hasMore: mockRefunds.length >= this.data.limit,
        page: this.data.page + 1
      });
      
      this.filterRefunds();

    } catch (error) {
      console.error('加载退款申请失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ 
        loading: false,
        refreshing: false 
      });
    }
  },

  /**
   * 筛选退款申请
   */
  filterRefunds() {
    let filtered = this.data.refunds;
    
    if (this.data.activeStatus) {
      const statusNum = parseInt(this.data.activeStatus);
      filtered = filtered.filter(refund => refund.status === statusNum);
    }
    
    this.setData({
      filteredRefunds: filtered
    });
  },

  /**
   * 按状态筛选
   */
  filterByStatus(e: any) {
    const status = e.currentTarget.dataset.status;
    this.setData({
      activeStatus: status
    });
    this.filterRefunds();
  },

  /**
   * 查看退款详情
   */
  async viewRefundDetail(e: any) {
    const refund = e.currentTarget.dataset.refund;
    
    // 如果需要详细信息，调用详情接口
    try {
      // const detailResponse = await MerchantAPI.getRefundDetail(refund.refundId);
      
      this.setData({
        showDetailModal: true,
        refundDetail: refund
      });
      
    } catch (error) {
      console.error('获取退款详情失败:', error);
      wx.showToast({
        title: '获取详情失败',
        icon: 'none'
      });
    }
  },

  /**
   * 处理退款申请
   */
  handleRefund(e: any) {
    const refund = e.currentTarget.dataset.refund;
    const action = e.currentTarget.dataset.action;
    
    this.setData({
      showReasonModal: true,
      processingRefund: refund,
      currentAction: action,
      processReason: ''
    });
  },

  /**
   * 从详情页面处理退款
   */
  handleDetailRefund(e: any) {
    const action = e.currentTarget.dataset.action;
    
    this.setData({
      showDetailModal: false,
      showReasonModal: true,
      processingRefund: this.data.refundDetail,
      currentAction: action,
      processReason: ''
    });
  },

  /**
   * 确认退款操作
   */
  async confirmRefundAction() {
    const { processingRefund, currentAction, processReason } = this.data;
    
    if (currentAction === 'reject' && !processReason.trim()) {
      wx.showToast({
        title: '请输入拒绝原因',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    try {
      // 调用后端API：/merchant/refund/applications/{refundId}/handle
      // await MerchantAPI.handleRefundApplication({
      //   refundId: processingRefund!.refundId,
      //   action: currentAction === 'approve' ? 1 : 2,
      //   reason: processReason
      // });

      // 更新本地数据
      const updatedRefunds = this.data.refunds.map(refund => {
        if (refund.refundId === processingRefund!.refundId) {
          return {
            ...refund,
            status: currentAction === 'approve' ? 2 : 3,
            statusText: currentAction === 'approve' ? '已退款' : '已拒绝'
          };
        }
        return refund;
      });

      // 更新统计数据
      const updatedStats = { ...this.data.stats };
      if (currentAction === 'approve') {
        updatedStats.pendingCount--;
        updatedStats.refundedCount++;
      } else {
        updatedStats.pendingCount--;
        updatedStats.processedCount++;
      }

      this.setData({
        refunds: updatedRefunds,
        stats: updatedStats,
        showReasonModal: false,
        processReason: ''
      });

      this.filterRefunds();

      wx.showToast({
        title: currentAction === 'approve' ? '退款申请已同意' : '退款申请已拒绝',
        icon: 'success'
      });

    } catch (error) {
      wx.showToast({
        title: '处理失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 预览凭证图片
   */
  previewEvidence(e: any) {
    const evidenceList = e.currentTarget.dataset.urls;
    const current = e.currentTarget.dataset.current;
    
    const urls = evidenceList.map((item: any) => item.url);
    
    wx.previewImage({
      urls: urls,
      current: current
    });
  },

  /**
   * 下拉刷新
   */
  onRefresh() {
    this.loadRefunds(true);
  },

  /**
   * 加载更多
   */
  loadMore() {
    if (!this.data.loading && this.data.hasMore) {
      this.loadRefunds();
    }
  },

  // 表单输入处理
  onReasonInput(e: any) {
    this.setData({
      processReason: e.detail.value
    });
  },

  // 弹窗控制
  closeDetailModal() {
    this.setData({
      showDetailModal: false
    });
  },

  closeReasonModal() {
    this.setData({
      showReasonModal: false,
      processReason: ''
    });
  },

  preventClose() {
    // 阻止事件冒泡
  },

  preventNavigation() {
    // 阻止卡片点击事件
  }
});

